/**
 * 播放器页面脚本
 */

// 全局变量
let mediaId = 0
let mediaTitle = ""
let playInfos = []
let currentFrom = ""
let currentUrl = ""
let currentIndex = 0
let videoPlayer = null
let isFullscreen = false
let playbackPosition = 0
let autoSaveInterval = null

// 假设 AppConfig 和 API 是通过某种方式引入的，例如：
// import { AppConfig } from './app-config.js';
// import { API } from './api.js';

// 如果不能使用 import，则假设它们是全局变量，并在此处声明
// 确保在实际环境中，这些变量被正确初始化
const AppConfig = window.AppConfig || {
  getConfig: () => ({
    player: {
      autoNext: true,
      rememberProgress: true,
      autoPlay: true,
    },
  }),
  getActiveSource: () => ({ id: "default" }),
}

const API = window.API || {
  getMediaDetail: async () => ({ vod_name: "Sample Video", vod_play_from: "default", vod_play_url: "url1$$url2" }),
  parsePlayUrls: (from, url) => [
    { from: "default", urls: [{ name: "Episode 1", url: "http://example.com/video1.mp4" }] },
  ],
  addPlayHistory: () => {},
}

document.addEventListener("DOMContentLoaded", () => {
  // 获取URL参数
  const urlParams = new URLSearchParams(window.location.search)
  mediaId = urlParams.get("id")
  currentFrom = urlParams.get("from") || ""
  currentUrl = urlParams.get("url") || ""

  if (!mediaId) {
    alert("缺少媒体ID")
    window.location.href = "index.html"
    return
  }

  // 初始化播放器
  initPlayer()

  // 初始化事件监听
  initEventListeners()

  // 加载媒体信息
  loadMediaInfo()
})

/**
 * 初始化播放器
 */
function initPlayer() {
  videoPlayer = document.getElementById("videoPlayer")

  if (!videoPlayer) return

  // 设置播放器事件
  videoPlayer.addEventListener("loadedmetadata", () => {
    // 恢复播放进度
    restorePlaybackPosition()
  })

  videoPlayer.addEventListener("timeupdate", () => {
    // 更新当前播放位置
    playbackPosition = videoPlayer.currentTime
  })

  videoPlayer.addEventListener("ended", () => {
    // 播放结束，自动播放下一集
    const config = AppConfig.getConfig()
    if (config.player.autoNext) {
      handleNextEpisode()
    }
  })

  // 设置自动保存播放进度
  const config = AppConfig.getConfig()
  if (config.player.rememberProgress) {
    autoSaveInterval = setInterval(() => {
      savePlaybackPosition()
    }, 5000) // 每5秒保存一次
  }
}

/**
 * 初始化事件监听
 */
function initEventListeners() {
  // 退出播放按钮
  const exitPlayer = document.getElementById("exitPlayer")
  if (exitPlayer) {
    exitPlayer.addEventListener("click", () => {
      // 保存播放进度
      savePlaybackPosition()

      // 返回详情页
      window.location.href = `detail.html?id=${mediaId}`
    })
  }

  // 上一集按钮
  const prevEpisode = document.getElementById("prevEpisode")
  if (prevEpisode) {
    prevEpisode.addEventListener("click", handlePrevEpisode)
  }

  // 下一集按钮
  const nextEpisode = document.getElementById("nextEpisode")
  if (nextEpisode) {
    nextEpisode.addEventListener("click", handleNextEpisode)
  }

  // 剧集列表按钮
  const episodeListToggle = document.getElementById("episodeListToggle")
  const episodeSidebar = document.getElementById("episodeSidebar")
  const sidebarOverlay = document.getElementById("sidebarOverlay")
  const closeSidebar = document.getElementById("closeSidebar")

  if (episodeListToggle && episodeSidebar && sidebarOverlay) {
    episodeListToggle.addEventListener("click", () => {
      episodeSidebar.classList.add("open")
      document.body.classList.add("episode-sidebar-open")
    })

    sidebarOverlay.addEventListener("click", () => {
      episodeSidebar.classList.remove("open")
      document.body.classList.remove("episode-sidebar-open")
    })

    if (closeSidebar) {
      closeSidebar.addEventListener("click", () => {
        episodeSidebar.classList.remove("open")
        document.body.classList.remove("episode-sidebar-open")
      })
    }
  }

  // 监听全屏变化
  document.addEventListener("fullscreenchange", handleFullscreenChange)
  document.addEventListener("webkitfullscreenchange", handleFullscreenChange)
  document.addEventListener("mozfullscreenchange", handleFullscreenChange)
  document.addEventListener("MSFullscreenChange", handleFullscreenChange)

  // 监听键盘事件
  document.addEventListener("keydown", handleKeyDown)

  // 监听页面离开事件
  window.addEventListener("beforeunload", () => {
    // 保存播放进度
    savePlaybackPosition()

    // 清除自动保存定时器
    if (autoSaveInterval) {
      clearInterval(autoSaveInterval)
    }
  })
}

/**
 * 加载媒体信息
 */
async function loadMediaInfo() {
  try {
    // 获取活跃源
    const activeSource = AppConfig.getActiveSource()
    if (!activeSource) {
      throw new Error("请先添加媒体源")
    }

    // 获取媒体详情
    const media = await API.getMediaDetail(activeSource, mediaId)
    if (!media) {
      throw new Error(`无法找到ID为 ${mediaId} 的内容`)
    }

    // 设置标题
    mediaTitle = media.vod_name
    document.title = `${mediaTitle} - 播放中`

    const playerTitle = document.getElementById("playerTitle")
    if (playerTitle) {
      playerTitle.textContent = mediaTitle
    }

    // 解析播放地址
    playInfos = API.parsePlayUrls(media.vod_play_from, media.vod_play_url)

    // 如果没有指定播放源和地址，使用第一个
    if (!currentFrom && playInfos.length > 0) {
      currentFrom = playInfos[0].from
    }

    if (!currentUrl && playInfos.length > 0) {
      const currentPlayInfo = playInfos.find((item) => item.from === currentFrom) || playInfos[0]
      if (currentPlayInfo.urls.length > 0) {
        currentUrl = currentPlayInfo.urls[0].url
      }
    }

    // 设置播放源
    const currentPlayInfo = playInfos.find((item) => item.from === currentFrom) || playInfos[0]
    const episodes = currentPlayInfo?.urls || []

    // 找到当前剧集索引
    currentIndex = episodes.findIndex((ep) => ep.url === currentUrl)
    if (currentIndex < 0) currentIndex = 0

    // 设置视频源
    if (videoPlayer && currentUrl) {
      videoPlayer.src = currentUrl
      videoPlayer.load()

      // 自动播放
      const config = AppConfig.getConfig()
      if (config.player.autoPlay) {
        try {
          await videoPlayer.play()
        } catch (error) {
          console.warn("自动播放失败:", error)
        }
      }
    }

    // 更新上一集/下一集按钮状态
    updateEpisodeButtons()

    // 渲染剧集列表
    renderEpisodeList()

    // 添加到播放历史
    API.addPlayHistory(media, currentFrom, currentUrl)
  } catch (error) {
    console.error("加载媒体信息失败:", error)
    alert(`加载失败: ${error.message || "未知错误"}`)
    window.location.href = "index.html"
  }
}

/**
 * 更新上一集/下一集按钮状态
 */
function updateEpisodeButtons() {
  const prevEpisode = document.getElementById("prevEpisode")
  const nextEpisode = document.getElementById("nextEpisode")

  if (!prevEpisode || !nextEpisode) return

  const currentPlayInfo = playInfos.find((item) => item.from === currentFrom) || playInfos[0]
  const episodes = currentPlayInfo?.urls || []

  // 上一集按钮
  prevEpisode.disabled = currentIndex <= 0

  // 下一集按钮
  nextEpisode.disabled = currentIndex >= episodes.length - 1
}

/**
 * 渲染剧集列表
 */
function renderEpisodeList() {
  const sourceButtons = document.getElementById("sourceButtons")
  const episodeGrid = document.getElementById("episodeGrid")

  if (!sourceButtons || !episodeGrid) return

  // 渲染播放源按钮
  sourceButtons.innerHTML = ""
  playInfos.forEach((source) => {
    const button = document.createElement("button")
    button.className = `source-button ${source.from === currentFrom ? "active" : ""}`
    button.textContent = source.from
    button.dataset.from = source.from

    button.addEventListener("click", () => {
      handleSourceChange(source.from)
    })

    sourceButtons.appendChild(button)
  })

  // 渲染剧集按钮
  episodeGrid.innerHTML = ""
  const currentPlayInfo = playInfos.find((item) => item.from === currentFrom) || playInfos[0]
  const episodes = currentPlayInfo?.urls || []

  episodes.forEach((episode, index) => {
    const button = document.createElement("a")
    button.href = `play.html?id=${mediaId}&from=${currentFrom}&url=${encodeURIComponent(episode.url)}`
    button.className = `episode-button ${index === currentIndex ? "active" : ""}`
    button.textContent = episode.name

    button.addEventListener("click", (e) => {
      e.preventDefault()
      handleEpisodeChange(episode.url, index)
    })

    episodeGrid.appendChild(button)
  })
}

/**
 * 处理播放源切换
 * @param {string} from 播放源
 */
function handleSourceChange(from) {
  if (from === currentFrom) return

  // 保存当前播放进度
  savePlaybackPosition()

  // 切换播放源
  currentFrom = from

  // 获取新播放源的剧集
  const newPlayInfo = playInfos.find((item) => item.from === from)
  if (newPlayInfo && newPlayInfo.urls.length > 0) {
    // 设置为第一集
    currentUrl = newPlayInfo.urls[0].url
    currentIndex = 0

    // 更新视频源
    if (videoPlayer) {
      videoPlayer.src = currentUrl
      videoPlayer.load()
      videoPlayer.play().catch((error) => console.warn("播放失败:", error))
    }

    // 更新上一集/下一集按钮状态
    updateEpisodeButtons()

    // 更新剧集列表
    renderEpisodeList()

    // 更新URL参数
    updateUrlParams()

    // 添加到播放历史
    const activeSource = AppConfig.getActiveSource()
    if (activeSource) {
      API.getMediaDetail(activeSource, mediaId).then((media) => {
        if (media) {
          API.addPlayHistory(media, currentFrom, currentUrl)
        }
      })
    }
  }
}

/**
 * 处理剧集切换
 * @param {string} url 剧集URL
 * @param {number} index 剧集索引
 */
function handleEpisodeChange(url, index) {
  if (url === currentUrl) return

  // 保存当前播放进度
  savePlaybackPosition()

  // 切换剧集
  currentUrl = url
  currentIndex = index

  // 更新视频源
  if (videoPlayer) {
    videoPlayer.src = currentUrl
    videoPlayer.load()
    videoPlayer.play().catch((error) => console.warn("播放失败:", error))
  }

  // 更新上一集/下一集按钮状态
  updateEpisodeButtons()

  // 更新剧集列表
  renderEpisodeList()

  // 更新URL参数
  updateUrlParams()

  // 添加到播放历史
  const activeSource = AppConfig.getActiveSource()
  if (activeSource) {
    API.getMediaDetail(activeSource, mediaId).then((media) => {
      if (media) {
        API.addPlayHistory(media, currentFrom, currentUrl)
      }
    })
  }

  // 关闭侧边栏
  const episodeSidebar = document.getElementById("episodeSidebar")
  if (episodeSidebar) {
    episodeSidebar.classList.remove("open")
    document.body.classList.remove("episode-sidebar-open")
  }
}

/**
 * 处理上一集
 */
function handlePrevEpisode() {
  const currentPlayInfo = playInfos.find((item) => item.from === currentFrom) || playInfos[0]
  const episodes = currentPlayInfo?.urls || []

  if (currentIndex > 0) {
    const prevIndex = currentIndex - 1
    const prevUrl = episodes[prevIndex].url
    handleEpisodeChange(prevUrl, prevIndex)
  }
}

/**
 * 处理下一集
 */
function handleNextEpisode() {
  const currentPlayInfo = playInfos.find((item) => item.from === currentFrom) || playInfos[0]
  const episodes = currentPlayInfo?.urls || []

  if (currentIndex < episodes.length - 1) {
    const nextIndex = currentIndex + 1
    const nextUrl = episodes[nextIndex].url
    handleEpisodeChange(nextUrl, nextIndex)
  }
}

/**
 * 处理全屏变化
 */
function handleFullscreenChange() {
  isFullscreen =
    !!document.fullscreenElement ||
    !!document.webkitFullscreenElement ||
    !!document.mozFullScreenElement ||
    !!document.msFullscreenElement

  // 可以在这里添加全屏状态的UI调整
}

/**
 * 处理键盘事件
 * @param {KeyboardEvent} e 键盘事件
 */
function handleKeyDown(e) {
  // 空格键：播放/暂停
  if (e.key === " " && videoPlayer) {
    e.preventDefault()
    if (videoPlayer.paused) {
      videoPlayer.play()
    } else {
      videoPlayer.pause()
    }
  }

  // 左箭头：后退10秒
  if (e.key === "ArrowLeft" && videoPlayer) {
    e.preventDefault()
    videoPlayer.currentTime = Math.max(0, videoPlayer.currentTime - 10)
  }

  // 右箭头：前进10秒
  if (e.key === "ArrowRight" && videoPlayer) {
    e.preventDefault()
    videoPlayer.currentTime = Math.min(videoPlayer.duration, videoPlayer.currentTime + 10)
  }

  // 上箭头：增加音量
  if (e.key === "ArrowUp" && videoPlayer) {
    e.preventDefault()
    videoPlayer.volume = Math.min(1, videoPlayer.volume + 0.1)
  }

  // 下箭头：减小音量
  if (e.key === "ArrowDown" && videoPlayer) {
    e.preventDefault()
    videoPlayer.volume = Math.max(0, videoPlayer.volume - 0.1)
  }

  // F键：全屏
  if (e.key === "f" || e.key === "F") {
    e.preventDefault()
    toggleFullscreen()
  }

  // ESC键：退出全屏（浏览器已内置）

  // P键或,键：上一集
  if ((e.key === "p" || e.key === "P" || e.key === ",") && !e.ctrlKey && !e.metaKey) {
    e.preventDefault()
    handlePrevEpisode()
  }

  // N键或.键：下一集
  if ((e.key === "n" || e.key === "N" || e.key === ".") && !e.ctrlKey && !e.metaKey) {
    e.preventDefault()
    handleNextEpisode()
  }

  // M键：静音
  if (e.key === "m" || e.key === "M") {
    e.preventDefault()
    if (videoPlayer) {
      videoPlayer.muted = !videoPlayer.muted
    }
  }
}

/**
 * 切换全屏
 */
function toggleFullscreen() {
  if (!videoPlayer) return

  if (!isFullscreen) {
    // 进入全屏
    if (videoPlayer.requestFullscreen) {
      videoPlayer.requestFullscreen()
    } else if (videoPlayer.webkitRequestFullscreen) {
      videoPlayer.webkitRequestFullscreen()
    } else if (videoPlayer.mozRequestFullScreen) {
      videoPlayer.mozRequestFullScreen()
    } else if (videoPlayer.msRequestFullscreen) {
      videoPlayer.msRequestFullscreen()
    }
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
  }
}

/**
 * 保存播放进度
 */
function savePlaybackPosition() {
  if (!videoPlayer || !mediaId || !currentFrom || !currentUrl) return

  const config = AppConfig.getConfig()
  if (!config.player.rememberProgress) return

  try {
    // 获取当前播放进度
    const position = videoPlayer.currentTime

    // 保存到本地存储
    const key = `playback_${mediaId}_${currentFrom}_${currentUrl}`
    localStorage.setItem(key, position.toString())

    // 更新播放历史
    const activeSource = AppConfig.getActiveSource()
    if (activeSource) {
      API.getMediaDetail(activeSource, mediaId).then((media) => {
        if (media) {
          API.addPlayHistory(media, currentFrom, currentUrl, position)
        }
      })
    }
  } catch (error) {
    console.error("保存播放进度失败:", error)
  }
}

/**
 * 恢复播放进度
 */
function restorePlaybackPosition() {
  if (!videoPlayer || !mediaId || !currentFrom || !currentUrl) return

  const config = AppConfig.getConfig()
  if (!config.player.rememberProgress) return

  try {
    // 从本地存储获取播放进度
    const key = `playback_${mediaId}_${currentFrom}_${currentUrl}`
    const savedPosition = localStorage.getItem(key)

    if (savedPosition) {
      const position = Number.parseFloat(savedPosition)

      // 如果进度超过了视频时长的95%，则从头开始播放
      if (position > videoPlayer.duration * 0.95) {
        videoPlayer.currentTime = 0
      } else {
        videoPlayer.currentTime = position
      }
    }
  } catch (error) {
    console.error("恢复播放进度失败:", error)
  }
}

/**
 * 更新URL参数
 */
function updateUrlParams() {
  const url = new URL(window.location.href)
  url.searchParams.set("from", currentFrom)
  url.searchParams.set("url", currentUrl)
  window.history.replaceState({}, "", url.toString())
}



/**
 * Custom Video Player Implementation
 */

class VideoPlayer {
  constructor(container, options = {}) {
    this.container = container;
    this.options = {
      autoPlay: true,
      volume: 1,
      muted: false,
      ...options
    };
    
    this.video = null;
    this.controls = null;
    this.progressBar = null;
    this.volumeControl = null;
    
    this.init();
  }
  
  init() {
    this.createElements();
    this.setupEventListeners();
    this.loadPreferences();
  }
  
  createElements() {
    // Create video element
    this.video = document.createElement('video');
    this.video.className = 'video-player';
    
    // Create controls container
    this.controls = document.createElement('div');
    this.controls.className = 'player-controls';
    
    // Create progress bar
    this.progressBar = document.createElement('div');
    this.progressBar.className = 'player-progress';
    this.progressBar.innerHTML = `
      <div class="progress-bar">
        <div class="progress-handle"></div>
      </div>
    `;
    
    // Create control buttons
    const controlButtons = document.createElement('div');
    controlButtons.className = 'player-buttons';
    controlButtons.innerHTML = `
      <button class="btn-player" data-action="play">
        <i class="ri-play-fill"></i>
      </button>
      <button class="btn-player" data-action="pause">
        <i class="ri-pause-fill"></i>
      </button>
      <button class="btn-player" data-action="prev">
        <i class="ri-skip-back-fill"></i>
      </button>
      <button class="btn-player" data-action="next">
        <i class="ri-skip-forward-fill"></i>
      </button>
      <button class="btn-player" data-action="volume">
        <i class="ri-volume-up-fill"></i>
      </button>
      <button class="btn-player" data-action="fullscreen">
        <i class="ri-fullscreen-line"></i>
      </button>
    `;
    
    // Assemble player
    this.controls.appendChild(controlButtons);
    this.controls.appendChild(this.progressBar);
    
    this.container.appendChild(this.video);
    this.container.appendChild(this.controls);
  }
  
  setupEventListeners() {
    // Video events
    this.video.addEventListener('loadedmetadata', () => this.onMetadataLoaded());
    this.video.addEventListener('timeupdate', () => this.onTimeUpdate());
    this.video.addEventListener('ended', () => this.onEnded());
    
    // Control events
    this.controls.addEventListener('click', (e) => this.handleControlClick(e));
    
    // Progress bar events
    this.progressBar.addEventListener('click', (e) => this.handleProgressClick(e));
    this.progressBar.addEventListener('mousedown', (e) => this.startDragging(e));
    
    // Keyboard events
    document.addEventListener('keydown', (e) => this.handleKeypress(e));
  }
  
  loadPreferences() {
    const config = window.AppConfig.getConfig();
    
    this.video.volume = config.player?.volume || 1;
    this.video.muted = config.player?.muted || false;
    
    if (config.player?.autoPlay) {
      this.play();
    }
  }
  
  // Player control methods
  play() {
    this.video.play();
    this.container.classList.add('playing');
  }
  
  pause() {
    this.video.pause();
    this.container.classList.remove('playing');
  }
  
  seek(time) {
    this.video.currentTime = time;
  }
  
  setVolume(volume) {
    this.video.volume = Math.max(0, Math.min(1, volume));
    this.savePreferences();
  }
  
  toggleMute() {
    this.video.muted = !this.video.muted;
    this.savePreferences();
  }
  
  toggleFullscreen() {
    if (!document.fullscreenElement) {
      this.container.requestFullscreen();
    } else {
      document.exitFullscreen();
    }
  }
  
  // Event handlers
  onMetadataLoaded() {
    this.updateProgress();
    this.updateDuration();
  }
  
  onTimeUpdate() {
    this.updateProgress();
  }
  
  onEnded() {
    if (this.options.autoPlay) {
      this.playNext();
    }
  }
  
  handleControlClick(e) {
    const action = e.target.closest('[data-action]')?.dataset.action;
    if (!action) return;
    
    switch(action) {
      case 'play':
        this.play();
        break;
      case 'pause':
        this.pause();
        break;
      case 'prev':
        this.playPrevious();
        break;
      case 'next':
        this.playNext();
        break;
      case 'volume':
        this.toggleMute();
        break;
      case 'fullscreen':
        this.toggleFullscreen();
        break;
    }
  }
  
  handleProgressClick(e) {
    const rect = this.progressBar.getBoundingClientRect();
    const pos = (e.clientX - rect.left) / rect.width;
    this.seek(pos * this.video.duration);
  }
  
  handleKeypress(e) {
    switch(e.key) {
      case ' ':
        this.video.paused ? this.play() : this.pause();
        break;
      case 'ArrowLeft':
        this.seek(this.video.currentTime - 10);
        break;
      case 'ArrowRight':
        this.seek(this.video.currentTime + 10);
        break;
      case 'ArrowUp':
        this.setVolume(this.video.volume + 0.1);
        break;
      case 'ArrowDown':
        this.setVolume(this.video.volume - 0.1);
        break;
    }
  }
  
  // Helper methods
  updateProgress() {
    const progress = (this.video.currentTime / this.video.duration) * 100;
    this.progressBar.querySelector('.progress-bar').style.width = `${progress}%`;
  }
  
  updateDuration() {
    const duration = this.formatTime(this.video.duration);
    this.controls.querySelector('.duration').textContent = duration;
  }
  
  formatTime(seconds) {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = Math.floor(seconds % 60);
    return `${h ? h + ':' : ''}${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
  }
  
  savePreferences() {
    const config = window.AppConfig.getConfig();
    config.player = {
      ...config.player,
      volume: this.video.volume,
      muted: this.video.muted
    };
    window.AppConfig.saveConfig(config);
  }
}

// Export player
window.VideoPlayer = VideoPlayer;